//
//  CLTopicModel.m
//  chanlin
//
//  Created by Ryan on 14-12-15.
//  Copyright (c) 2014年 chanlin. All rights reserved.
//

#import "CLTopicModel.h"
#import "CLTopic.h"
#import "CLTopic+Oper.h"
#import "IFCoreDataManager.h"
#import "IFLabel2.h"
#import "CLUrl.h"

@implementation CLTopicModel

SGR_DEF_SINGLETION(CLTopicModel)

- (void)getListWithTopicId:(NSString *)topicId
                   uiBlock:(void (^)(BOOL success,id responseObj,NSString *message) )block{
    NSString *url=[NSString stringWithFormat:[self urlWithCategory:@"topic"],topicId];
    NSAssert(url!=nil, @"url not be null");
    __block BOOL isSuccess;
    __block NSString *errormessage;
    [self getWithUrl:url param:nil dataBlock:^(BOOL success, id responseObj, NSError *message, NSMutableDictionary *param) {
        if(success && [responseObj isKindOfClass:[NSDictionary class]]&&
           1==[responseObj sgrGetIntForKey:@"status"]){
            [[IFCoreDataManager sharedInstance] performBlockAndWait:^(NSManagedObjectContext *moc) {
                NSArray *array=[CLTopic fetchAllWithPredict:[NSPredicate predicateWithFormat:@"topicId==%@",topicId]
                                                    withMOC:moc];
                if(array){
                    for(CLTopic *item in array){
                        [moc deleteObject:item];
                    }
                }
                
                NSString *ztpic=[responseObj sgrGetStringForKey:@"ztpic"];
                if(_isStrNotNull(ztpic)){
                    CLTopic *topic=[CLTopic managerObjWithMoc:moc];
                    topic.topicId=topicId;
                    topic.style=CLList_style_topic_img;
                    topic.thumnail=ztpic;
                    topic.cHeight=100.f;
                    topic.sort=0;
                    topic.area=@"0";
                }
                
                NSString *smalltext=[responseObj sgrGetStringForKey:@"smalltext"];
                NSString *smatTitle=[responseObj sgrGetStringForKey:@"smalltext_title"];
                if(_isStrNotNull(smalltext)){
                    CLTopic *topic=[CLTopic managerObjWithMoc:moc];
                    topic.topicId=topicId;
                    topic.title=smalltext;
                    topic.style=CLList_style_topic_text;
                    topic.slider1=smatTitle;
                    topic.thumnail=ztpic;
                    topic.sort=1;
                    topic.area=@"0";
                    topic.cHeight=[IFLabel2 suggestHeightOfString:smalltext withWidth:275.f font:[UIFont systemFontOfSize:16] lineSpace:0]+38+22;
                }
                
                
                NSArray *focus=[((NSObject *)responseObj) sgrGetArrayForKey:@"focus"];
                
                if([focus count]>0){
                    CLTopic *focusItem=[CLTopic managerObjWithMoc:moc];
                    focusItem.itemId=@"focus";
                    focusItem.style=CLList_style_focus;
                    focusItem.cHeight=180.f;
                    //focusItem.category=[category sgrGetStringForKey:@"channelId"];
                    focusItem.sort=2;
                    focusItem.topicId=topicId;
                    focusItem.area=@"0";
                    NSUInteger n=[focus count];
                    
                    NSMutableOrderedSet *set=[NSMutableOrderedSet orderedSet];
                    
                    for(int i=0;i<n;i++){
                        NSDictionary *dic=[focus sgrGetDictionaryForIndex:i];
                        if(!dic)continue;
                        CLTopic *listitem=[CLTopic managerObjWithMoc:moc];
                        [listitem proInitwithDictionary:dic];
                        listitem.style=CLList_style_doc;
                        //listitem.category=@"focus";
                        
                        [set addObject:listitem];
                        //[focusItem addFocusObject:listitem];
                        
                    }
                    
                    if(set.count>0)
                        focusItem.focus=set;
                }

                
                
                NSArray *list=[responseObj sgrGetArrayForKey:@"list"];
                
                NSDictionary *cmts=[responseObj sgrGetDictionaryForKey:@"comments"];
                
                NSUInteger n=[list count];
                int last=1;
                for(int i=0;i<n;i++){
                    NSDictionary *dic=[list sgrGetDictionaryForIndex:i];
                    if(!dic)continue;
              
                    CLTopic *listitem=[CLTopic managerObjWithMoc:moc];
                    listitem.sort=i+3+last;
                    [listitem proInitwithDictionary:dic];
                    
                    listitem.comment=[[cmts sgrGetDictionaryForKey:listitem.itemId] sgrGetIntForKey:@"comments"];
             
                    listitem.topicId=topicId;
                    
                    NSArray *imgs=[dic sgrGetArrayForKey:@"morepic"];
                    if(imgs.count>0){
                        if(listitem.subtopicUrl){
                            for(CLUrl *url in listitem.subtopicUrl){
                                [moc deleteObject:url];
                            }
                            NSMutableOrderedSet *set=[NSMutableOrderedSet orderedSet];
                            for(NSString *str in imgs){
                                CLUrl *url=[CLUrl managerObjWithMoc:moc];
                                url.url=str;
                                [set addObject:url];
                                
                            }
                            listitem.subtopicUrl=set;
                            
                        }
                    }

                    
                }
                [[IFCoreDataManager sharedInstance] saveContext:moc ToPersistentStore:nil];
                isSuccess=YES;

            
            }];
        }else{
            isSuccess=NO;
            errormessage=@"数据错误!";
        }
    } uiBlock:^(BOOL success, id responseObj, NSError *message, NSMutableDictionary *param) {
        block(isSuccess,responseObj,errormessage);
    }];
}


- (void)getDoListWithClassId:(NSString *)topicId
                         url:(NSString *)url
                      page:(int)num
                 lastTopic:(CLTopic *)topic
                     uiBlock:(void (^)(BOOL success,id responseObj,NSString *message) )block{
    if(num>1){
        url=[url stringByAppendingFormat:@"&page=%d",num];
    }
    __block BOOL isSuccess;
    __block NSString *errormessage;
    [self getWithUrl:url
               param:nil
           dataBlock:^(BOOL success, id responseObj, NSError *message, NSMutableDictionary *param) {
               if(success && [responseObj isKindOfClass:[NSDictionary class]]&&
                  1==[responseObj sgrGetIntForKey:@"status"]){
                   [param sgrSetObject:[responseObj sgrGetStringForKey:@"img"] forKey:@"headImg"];
                   [[IFCoreDataManager sharedInstance] performBlockAndWait:^(NSManagedObjectContext *moc) {
                       
                       NSString *cateId=[NSString stringWithFormat:@"sub%@",topicId];
                       
                       if(num==1){
                           NSArray *array=[CLTopic fetchAllWithPredict:[NSPredicate predicateWithFormat:@"topicId==%@",cateId]
                                                               withMOC:moc];
                           
                           if(array){
                               for(CLTopic *item in array){
                                   [moc deleteObject:item];
                               }
                           }
                       }
                       
                       NSArray *list=[responseObj sgrGetArrayForKey:@"list"];
                       int last=topic?topic.sort+1:0;
                       
                       NSUInteger n=[list count];
                       
                       for(int i=0;i<n;i++){
                           NSDictionary *dic=[list sgrGetDictionaryForIndex:i];
                           NSString *itemId=[dic sgrGetStringForKey:@"id"];
                           NSArray *arra=[CLTopic fetchAllWithPredict:
                                          [NSPredicate predicateWithFormat:@"topicId==%@ and itemId=%@",cateId,itemId]
                                                              withMOC:moc];
                           if(arra && [arra count]>0)continue;
                           CLTopic *topic=[CLTopic managerObjWithMoc:moc];
                           [topic proInitwithDictionary:dic];
                           topic.topicId=cateId;
                           topic.sort=i+1+last;
                           NSArray *imgs=[dic sgrGetArrayForKey:@"morepic"];
                           if(imgs.count>0){
                               if(topic.subtopicUrl){
                                   for(CLUrl *url in topic.subtopicUrl){
                                       [moc deleteObject:url];
                                   }
                                   NSMutableOrderedSet *set=[NSMutableOrderedSet orderedSet];
                                   for(NSString *str in imgs){
                                       CLUrl *url=[CLUrl managerObjWithMoc:moc];
                                       url.url=str;
                                       [set addObject:url];
                                       
                                   }
                                   topic.subtopicUrl=set;
                                   
                               }
                           }
                           
                       }
                       
                       [[IFCoreDataManager sharedInstance] saveContext:moc ToPersistentStore:nil];
                       isSuccess=YES;
                       
                       
                       
                   }];
                   
                   
               }else{
                   isSuccess=NO;
                   errormessage=@"数据错误!";
               }
           } uiBlock:^(BOOL success, id responseObj, NSError *message, NSMutableDictionary *param) {
               block(isSuccess,param,errormessage);
           }];

}

- (void)getWlistWithClassId:(NSString *)topicId
                       page:(int)num
                  lastTopic:(CLTopic *)topic
                    uiBlock:(void (^)(BOOL success,id responseObj,NSString *message) )block{
    NSString *url=nil;
    
    url=[NSString stringWithFormat:@"http://appv2.chanlin.org/e/app/wlist.php?cid=%@",topicId];
    
    [self getDoListWithClassId:topicId url:url page:num lastTopic:topic uiBlock:block];
}

- (void)getBlistWithClassId:(NSString *)topicId
                       page:(int)num
                  lastTopic:(CLTopic *)topic
                    uiBlock:(void (^)(BOOL success,id responseObj,NSString *message) )block{
    NSString *url=nil;
    
    url=[NSString stringWithFormat:@"http://appv2.chanlin.org/e/app/blist.php?id=%@",topicId];
    
    [self getDoListWithClassId:topicId url:url page:num lastTopic:topic uiBlock:block];
}

- (void)getListWithClassId:(NSString *)topicId
                      page:(int)num
                 lastTopic:(CLTopic *)topic
                   uiBlock:(void (^)(BOOL success,id responseObj,NSString *message) )block{
    NSString *url=nil;
  
    url=[NSString stringWithFormat:@"http://appv2.chanlin.org/e/app/rlist.php?cid=%@",topicId];

    [self getDoListWithClassId:topicId url:url page:num lastTopic:topic uiBlock:block];
}

@end
